<template>
  <div class="attendance-exception-container">
    <el-card class="page-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Warning /></el-icon>
            <span class="header-title">考勤异常管理</span>
          </div>
          <div class="header-right">
            <el-button type="success" @click="exportData" :loading="exportLoading">
              <el-icon><Download /></el-icon>
              导出Excel
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 统计卡片 -->
      <div class="statistics-cards" v-if="userRole === 'HR' || userRole === 'MANAGER'">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-label">总异常数</div>
                <div class="stat-value">{{ exceptionStats.totalExceptions || 0 }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-label">迟到</div>
                <div class="stat-value danger">{{ exceptionStats.lateCount || 0 }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-label">早退</div>
                <div class="stat-value warning">{{ exceptionStats.earlyLeaveCount || 0 }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-label">缺勤</div>
                <div class="stat-value danger">{{ exceptionStats.absentCount || 0 }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-label">未处理</div>
                <div class="stat-value warning">{{ exceptionStats.unhandledCount || 0 }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-label">已处理</div>
                <div class="stat-value success">{{ exceptionStats.handledCount || 0 }}</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <el-divider v-if="userRole === 'HR' || userRole === 'MANAGER'" />
      
      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="月份">
            <el-date-picker
              v-model="filterForm.month"
              type="month"
              placeholder="选择月份"
              format="YYYY-MM"
              value-format="YYYY-MM"
              size="large"
              @change="loadExceptionList"
            />
          </el-form-item>
          <el-form-item label="异常类型">
            <el-select 
              v-model="filterForm.exceptionType" 
              placeholder="全部" 
              clearable 
              size="large" 
              @change="loadExceptionList"
              style="width: 150px"
            >
              <el-option label="全部" value="" />
              <el-option label="迟到" value="LATE" />
              <el-option label="早退" value="EARLY_LEAVE" />
            </el-select>
          </el-form-item>
          <el-form-item label="处理状态">
            <el-select 
              v-model="filterForm.exceptionStatus" 
              placeholder="全部" 
              clearable 
              size="large" 
              @change="loadExceptionList"
              style="width: 150px"
            >
              <el-option label="全部" value="" />
              <el-option label="未处理" value="UNHANDLED" />
              <el-option label="已处理" value="HANDLED" />
              <el-option label="已忽略" value="IGNORED" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadExceptionList" size="large">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetFilter" size="large">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 异常记录列表 -->
      <div class="table-section">
        <el-table 
          :data="exceptionList" 
          style="width: 100%"
          stripe
          :empty-text="'暂无异常记录'"
          v-loading="loading"
        >
          <el-table-column label="员工" width="150" align="center" v-if="userRole === 'HR' || userRole === 'MANAGER'">
            <template #default="scope">
              <span>{{ scope.row.userName || `员工${scope.row.userId}` }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="attendanceDate" label="考勤日期" width="120" align="center">
            <template #default="scope">
              <span>{{ formatDate(scope.row.attendanceDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="异常类型" width="150" align="center">
            <template #default="scope">
              <div class="exception-tags">
                <el-tag v-if="scope.row.isLate" type="danger" size="small">
                  迟到{{ scope.row.lateMinutes }}分钟
                </el-tag>
                <el-tag v-if="scope.row.isEarlyLeave" type="warning" size="small">
                  早退{{ scope.row.earlyLeaveMinutes }}分钟
                </el-tag>
                <el-tag v-if="scope.row.isAbsent" type="danger" size="small">
                  缺勤
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="exceptionReason" label="异常原因" min-width="200" align="center">
            <template #default="scope">
              <span>{{ scope.row.exceptionReason || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="checkInTime" label="打卡时间" width="180" align="center">
            <template #default="scope">
              <div v-if="scope.row.checkInTime">
                <div>上班：{{ formatDateTime(scope.row.checkInTime) }}</div>
              </div>
              <div v-if="scope.row.checkOutTime">
                <div>下班：{{ formatDateTime(scope.row.checkOutTime) }}</div>
              </div>
              <span v-if="!scope.row.checkInTime && !scope.row.checkOutTime">-</span>
            </template>
          </el-table-column>
          <el-table-column label="处理状态" width="120" align="center">
            <template #default="scope">
              <el-tag v-if="!scope.row.exceptionStatus || scope.row.exceptionStatus === 'UNHANDLED'" type="warning">
                未处理
              </el-tag>
              <el-tag v-else-if="scope.row.exceptionStatus === 'HANDLED'" type="success">
                已处理
              </el-tag>
              <el-tag v-else-if="scope.row.exceptionStatus === 'IGNORED'" type="info">
                已忽略
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="处理备注" min-width="200" align="center" v-if="userRole === 'HR' || userRole === 'MANAGER'">
            <template #default="scope">
              <span>{{ scope.row.exceptionHandleRemark || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="处理时间" width="180" align="center" v-if="userRole === 'HR' || userRole === 'MANAGER'">
            <template #default="scope">
              <span>{{ scope.row.exceptionHandleTime ? formatDateTime(scope.row.exceptionHandleTime) : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center" v-if="userRole === 'HR' || userRole === 'MANAGER'">
            <template #default="scope">
              <el-button 
                v-if="!scope.row.exceptionStatus || scope.row.exceptionStatus === 'UNHANDLED'"
                type="primary" 
                size="small" 
                @click="showHandleDialog(scope.row)"
              >
                处理
              </el-button>
              <el-button 
                v-else
                type="info" 
                size="small" 
                @click="showHandleDialog(scope.row)"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    
    <!-- 处理异常弹窗 -->
    <el-dialog
      v-model="showHandleDialogVisible"
      :title="currentRecord ? '处理异常' : ''"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="handleFormRef"
        :model="handleForm"
        :rules="handleRules"
        label-width="120px"
      >
        <el-form-item label="员工" v-if="currentRecord">
          <span>{{ currentRecord.userName || `员工${currentRecord.userId}` }}</span>
        </el-form-item>
        <el-form-item label="考勤日期" v-if="currentRecord">
          <span>{{ formatDate(currentRecord.attendanceDate) }}</span>
        </el-form-item>
        <el-form-item label="异常类型" v-if="currentRecord">
          <div class="exception-tags dialog-tags">
            <el-tag v-if="currentRecord.isLate" type="danger" size="small">
              迟到{{ currentRecord.lateMinutes }}分钟
            </el-tag>
            <el-tag v-if="currentRecord.isEarlyLeave" type="warning" size="small">
              早退{{ currentRecord.earlyLeaveMinutes }}分钟
            </el-tag>
            <el-tag v-if="currentRecord.isAbsent" type="danger" size="small">
              缺勤
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="异常原因" v-if="currentRecord">
          <div class="exception-reason-text">{{ currentRecord.exceptionReason || '-' }}</div>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-radio-group v-model="handleForm.status">
            <el-radio label="HANDLED">已处理</el-radio>
            <el-radio label="IGNORED">已忽略</el-radio>
            <el-radio label="UNHANDLED">未处理</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理备注" prop="remark">
          <el-input
            v-model="handleForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入处理备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showHandleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleException" :loading="handleLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import request from '../utils/request'
import { ElMessage } from 'element-plus'
import { Warning, Search, Refresh, Download } from '@element-plus/icons-vue'

export default {
  name: 'AttendanceException',
  components: {
    Warning,
    Search,
    Refresh,
    Download
  },
  setup() {
    const exceptionList = ref([])
    const exceptionStats = ref({})
    const loading = ref(false)
    const handleLoading = ref(false)
    const exportLoading = ref(false)
    const showHandleDialogVisible = ref(false)
    const currentRecord = ref(null)
    const handleFormRef = ref(null)
    
    const userRole = computed(() => {
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      return userInfo.role || 'EMPLOYEE'
    })
    
    const filterForm = ref({
      month: '',
      exceptionType: '',
      exceptionStatus: ''
    })
    
    const handleForm = ref({
      status: 'HANDLED',
      remark: ''
    })
    
    const handleRules = {
      status: [
        { required: true, message: '请选择处理状态', trigger: 'change' }
      ]
    }
    
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return date.toLocaleDateString('zh-CN')
    }
    
    const formatDateTime = (dateStr) => {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return date.toLocaleString('zh-CN', { 
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    // 加载异常统计
    const loadExceptionStatistics = async () => {
      if (userRole.value !== 'HR' && userRole.value !== 'MANAGER') {
        return
      }
      
      try {
        const params = {}
        if (filterForm.value.month) {
          params.month = filterForm.value.month
        }
        const res = await request.get('/attendance/exception/statistics', { params })
        if (res.code === 200) {
          exceptionStats.value = res.data || {}
        }
      } catch (error) {
        console.error('加载异常统计失败', error)
      }
    }
    
    // 加载异常列表
    const loadExceptionList = async () => {
      loading.value = true
      try {
        const params = {}
        if (filterForm.value.month) {
          params.month = filterForm.value.month
        }
        if (filterForm.value.exceptionType) {
          params.exceptionType = filterForm.value.exceptionType
        }
        if (filterForm.value.exceptionStatus) {
          params.exceptionStatus = filterForm.value.exceptionStatus
        }
        
        const res = await request.get('/attendance/exception', { params })
        if (res.code === 200) {
          exceptionList.value = res.data || []
        } else {
          ElMessage.error(res.message || '加载异常记录失败')
        }
      } catch (error) {
        ElMessage.error('加载异常记录失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    }
    
    // 重置筛选条件
    const resetFilter = () => {
      filterForm.value = {
        month: '',
        exceptionType: '',
        exceptionStatus: ''
      }
      loadExceptionList()
      loadExceptionStatistics()
    }
    
    // 显示处理弹窗
    const showHandleDialog = (record) => {
      currentRecord.value = record
      handleForm.value = {
        status: record.exceptionStatus || 'UNHANDLED',
        remark: record.exceptionHandleRemark || ''
      }
      showHandleDialogVisible.value = true
    }
    
    // 导出数据
    const exportData = async () => {
      exportLoading.value = true
      try {
        const params = {}
        if (filterForm.value.month) {
          params.month = filterForm.value.month
        }
        if (filterForm.value.exceptionType) {
          params.exceptionType = filterForm.value.exceptionType
        }
        if (filterForm.value.exceptionStatus) {
          params.exceptionStatus = filterForm.value.exceptionStatus
        }
        
        const token = localStorage.getItem('token')
        const queryString = new URLSearchParams(params).toString()
        const url = `/api/attendance/exception/export${queryString ? '?' + queryString : ''}`
        
        const response = await fetch(url, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (!response.ok) {
          throw new Error('导出失败')
        }
        
        const blob = await response.blob()
        const downloadUrl = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = downloadUrl
        const fileName = `考勤异常记录_${filterForm.value.month || new Date().toISOString().slice(0, 7)}.xlsx`
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(downloadUrl)
        
        ElMessage.success('导出成功')
      } catch (error) {
        ElMessage.error('导出失败：' + (error.message || '未知错误'))
      } finally {
        exportLoading.value = false
      }
    }
    
    // 处理异常
    const handleException = async () => {
      if (!handleFormRef.value) return
      
      try {
        await handleFormRef.value.validate()
        handleLoading.value = true
        
        const res = await request.post('/attendance/exception/handle', {
          recordId: currentRecord.value.id,
          status: handleForm.value.status,
          remark: handleForm.value.remark
        })
        
        if (res.code === 200) {
          ElMessage.success('处理成功')
          showHandleDialogVisible.value = false
          loadExceptionList()
          loadExceptionStatistics()
        } else {
          ElMessage.error(res.message || '处理失败')
        }
      } catch (error) {
        if (error.response && error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('处理失败')
        }
      } finally {
        handleLoading.value = false
      }
    }
    
    onMounted(() => {
      // 设置默认月份为当前月份
      const now = new Date()
      const month = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
      filterForm.value.month = month
      
      loadExceptionList()
      loadExceptionStatistics()
    })
    
    return {
      exceptionList,
      exceptionStats,
      loading,
      handleLoading,
      exportLoading,
      showHandleDialogVisible,
      currentRecord,
      handleFormRef,
      userRole,
      filterForm,
      handleForm,
      handleRules,
      formatDate,
      formatDateTime,
      loadExceptionList,
      resetFilter,
      showHandleDialog,
      handleException,
      loadExceptionStatistics,
      exportData
    }
  }
}
</script>

<style scoped>
.attendance-exception-container {
  width: 100%;
  height: 100%;
}

.page-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 24px;
  color: #e6a23c;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.statistics-cards {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-content {
  text-align: center;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #409eff;
}

.stat-value.success {
  color: #67c23a;
}

.stat-value.warning {
  color: #e6a23c;
}

.stat-value.danger {
  color: #f56c6c;
}

.filter-section {
  margin-bottom: 24px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.table-section {
  margin-top: 24px;
}

.exception-tags {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 16px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 弹窗中的异常标签样式 */
.dialog-tags {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 8px;
  align-items: flex-start;
  width: 100%;
}

/* 弹窗中的异常原因文本样式 */
.exception-reason-text {
  word-wrap: break-word;
  word-break: break-all;
  white-space: pre-wrap;
  max-width: 100%;
  line-height: 1.6;
  color: #606266;
}
</style>

